package com.plian.system.task.BondsRepayment;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.plian.Tools.StringUtil;
import com.plian.Tools.pagedata.PageData;
import com.plian.system.dao.cqzc.bondsrepayment.BondsRepaymentDao;
import com.plian.system.dao.sys.user.UserDao;
import com.plian.system.entity.ms.RectificationSituation;
import com.plian.system.entity.sys.UserOrg;
import com.plian.system.entity.taskMsg.ScheduledTasksMsg;
import com.plian.system.mapper.tasksMsg.ScheduledTasksMsgMapper;
import com.plian.system.model.page.Page;
import com.plian.system.service.ms.IRectificationSituationService;
import com.plian.system.service.sys.user.IUserOrgService;
import com.plian.system.service.tasksMsg.IScheduledTasksMsgService;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.joda.time.Days;
import org.joda.time.LocalDate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Scheduled;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**定时弹窗
 * @Author：zsk
 * @Package：com.plian.system.task.BondsRepayment
 * @Project：xt-gzw
 * @name：BondsRepaymentTask
 * @Date：2025/2/17 9:55
 * @Filename：BondsRepaymentTask
 */
@Configuration
public class BondsRepaymentTask {
    private static final Logger log = LoggerFactory.getLogger(BondsRepaymentTask.class);
    @Resource
    private IRectificationSituationService iRectificationSituationService;
    @Resource
    private IScheduledTasksMsgService iScheduledTasksMsgService;
    @Resource
    private UserDao userDao;
    @Resource
    private IUserOrgService iUserOrgService;
    private String moduleType="zqch";
    @Resource
    private ScheduledTasksMsgMapper scheduledTasksMsgMapper;
    @Resource
    private BondsRepaymentDao bondsrepaymentDao;

    @Scheduled(cron = "0 0 0 1 * ?")
    private void configureTasks() {
        log.info("债券偿还预警定时任务开始时间为："+new Date());
        Page page = new Page(false, new PageData());
        QueryWrapper<ScheduledTasksMsg> situationQueryWrapperQueryWrapper = new QueryWrapper<>();
        situationQueryWrapperQueryWrapper.eq("module_type",moduleType);
        situationQueryWrapperQueryWrapper.eq("is_deleted",0);
        List<ScheduledTasksMsg> list1=iScheduledTasksMsgService.list(situationQueryWrapperQueryWrapper);
        if(list1!=null&&list1.size()>0){
            List<Long> longs=new ArrayList<>();
            for (ScheduledTasksMsg scheduledTasksMsg: list1) {
                longs.add(scheduledTasksMsg.getId());
            }
            if(longs!=null&&longs.size()>0){
                scheduledTasksMsgMapper.deleteByIds(longs);//进来之后先删除
            }
        }
        try {
            List<PageData> list = bondsrepaymentDao.reportListPageSix(page);
            if(list!=null&&list.size()>0){
                for (PageData pageData: list) {
                    if(pageData!=null&&StringUtil.isNotBlank(pageData.getString("repaymentDate"))&&StringUtil.isNotBlank(pageData.getString("orgId"))){
                        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                        Date repaymentDate = dateFormat.parse(pageData.getString("repaymentDate"));
                        String repaymentDateStr=dateFormat.format(repaymentDate);
                        Long days=calculateDaysBetween(dateFormat.format(new Date()),pageData.getString("repaymentDate"));
                        String msgCountent="债券偿还(单据编码："+pageData.getString("code")+",发行债券名称:"+pageData.getString("issueName")+",偿还日期："+repaymentDateStr+")还有"+days+"天到偿还日期,请尽快偿还;";
                        QueryWrapper<UserOrg> userOrgQueryWrapper = new QueryWrapper<>();
                        userOrgQueryWrapper.eq("ORGID",pageData.getString("orgId"));
                        List<UserOrg> userOrgList=iUserOrgService.list(userOrgQueryWrapper);
                        if(userOrgList!=null&&userOrgList.size()>0){
                            for (UserOrg userOrg: userOrgList) {
                                PageData pageDataUser=userDao.findbyid(userOrg.getUserId());
                                if(pageDataUser!=null&&StringUtil.isNotBlank(pageDataUser.getString("isGroupAdmin"))&&pageDataUser.getString("isGroupAdmin").equals("1")){
                                    ScheduledTasksMsg scheduledTasksMsg=new ScheduledTasksMsg();
                                    scheduledTasksMsg.setStatus(0);
                                    scheduledTasksMsg.setOrgId(pageData.getString("orgId"));
                                    scheduledTasksMsg.setExternalCode(pageData.getString("code"));
                                    scheduledTasksMsg.setExternalId(pageData.getString("id"));
                                    scheduledTasksMsg.setMsgContent(msgCountent);
                                    scheduledTasksMsg.setUserId(pageDataUser.getString("id"));
                                    scheduledTasksMsg.setUserName(pageDataUser.getString("username"));
                                    scheduledTasksMsg.setCreateTime(new Date());
                                    scheduledTasksMsg.setUpdateTime(new Date());
                                    scheduledTasksMsg.setModuleType(moduleType);
                                    iScheduledTasksMsgService.save(scheduledTasksMsg);
                                }
                            }
                        }
                    }
                }

            }
        }catch (Exception e){
            log.error(ExceptionUtils.getStackTrace(e));
        }
    }
    public  Long calculateDaysBetween(String startDateString, String endDateString) throws ParseException {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date startDate = dateFormat.parse(startDateString);
        Date endDate = dateFormat.parse(endDateString);
        Long diffMillis = endDate.getTime() - startDate.getTime();
        return TimeUnit.DAYS.convert(diffMillis, TimeUnit.MILLISECONDS);
    }

}
